//-----------------------------------------------------------------------
// <copyright file="Parse.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation.  All rights reserved.
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY 
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
// </copyright>
// <author>Steven Sloggett (Charteris)</author>
// <email>v-stslog</email>
// <date>2007-03-13</date>
// <summary>Parses a version number from some text. Useful when the version number is generated by an external source.</summary>
//-----------------------------------------------------------------------

namespace Microsoft.Sdc.Tasks.VersionNumber
{
    using System;
    using System.Globalization;
    using System.IO;
    using System.Text.RegularExpressions;

    using Microsoft.Build.Framework;

    /// <summary>
    /// Parses a version number from some text. Useful when the version number is generated by an external source.
    /// </summary>
    /// <remarks>
    /// <code><![CDATA[
    /// <VersionNumber.Parse
    ///     Text="text"
    ///     VersionNamePath="versionNamePath">
    ///     <Output TaskParameter="VersionNumber" PropertyName="versionNumber" />
    ///     <Output TaskParameter="VersionName" PropertyName="versionName" />
    ///     <Output TaskParameter="MajorNumber" PropertyName="majorNumber" />
    ///     <Output TaskParameter="MinorNumber" PropertyName="minorNumber" />
    ///     <Output TaskParameter="BuildNumber" PropertyName="buildNumber" />
    ///     <Output TaskParameter="RevisionNumber" PropertyName="revisionNumber" />
    /// </VersionNumber.Parse>
    /// ]]></code>
    /// <para>where:</para>
    /// <para><i>text (Required)</i></para>
    /// <para>The text containing the version number.</para>
    /// <para><i>versionNamePath</i></para>
    /// <para>The path to the root folder for the current version.</para>
    /// <para><i>versionNumber (Output)</i></para>
    /// <para>The full version number containing the major, minor, build and revision numbers.</para>
    /// <para><i>versionName (Output)</i></para>
    /// <para>The name of the current version.</para>
    /// <para><i>majorNumber (Output)</i></para>
    /// <para>The major number for the version.</para>
    /// <para><i>minorNumber (Output)</i></para>
    /// <para>The minor number for the version.</para>
    /// <para><i>buildNumber (Output)</i></para>
    /// <para>The build number for the version.</para>
    /// <para><i>revisionNumber (Output)</i></para>
    /// <para>The revision number for the version.</para>
    /// </remarks>
    /// <example>
    /// <code><![CDATA[
    /// <Project>
    ///     <PropertyGroup>
    ///         <Text>The version number is 1.2.0.6896 in this test.</Text>
    ///         <VersionNamePath>$(MSBuildProjectDirectory)\..\..</VersionNamePath>
    ///     </PropertyGroup>
    ///
    ///     <Target Name="Test">
    ///         <VersionNumber.Parse
    ///             Text="$(Text)"
    ///             VersionNamePath="$(VersionNamePath)">
    ///             <Output TaskParameter="VersionNumber" PropertyName="VersionNumber" />
    ///             <Output TaskParameter="VersionName" PropertyName="VersionName" />
    ///             <Output TaskParameter="MajorNumber" PropertyName="MajorNumber" />
    ///             <Output TaskParameter="MinorNumber" PropertyName="MinorNumber" />
    ///             <Output TaskParameter="BuildNumber" PropertyName="BuildNumber" />
    ///             <Output TaskParameter="RevisionNumber" PropertyName="RevisionNumber" />
    ///         </VersionNumber.Parse>
    ///
    ///         <Message Text="Text: $(Text)" />
    ///         <Message Text="VersionNamePath: $(VersionNamePath)" />
    ///
    ///         <Message Text="VersionNumber: $(VersionNumber)" Importance="high" />
    ///         <Message Text="VersionName: $(VersionName)" Importance="high" />
    ///         <Message Text="MajorNumber: $(MajorNumber)" Importance="high" />
    ///         <Message Text="MinorNumber: $(MinorNumber)" Importance="high" />
    ///         <Message Text="BuildNumber: $(BuildNumber)" Importance="high" />
    ///         <Message Text="RevisionNumber: $(RevisionNumber)" Importance="high" />
    ///     </Target>
    /// </Project>
    /// ]]></code>    
    /// </example>
    public class Parse : TaskBase
    {
        /// <summary>
        /// The regular expression to match a version number.
        /// </summary>
        private const string VersionNumberRegularExpression = @"\d+\.\d+(\.\d+(\.\d+)?)?";

        /// <summary>
        /// The full version number.
        /// </summary>
        private Version version;

        /// <summary>
        /// The name of the current version.
        /// </summary>
        private string versionName;

        /// <summary>
        /// The path to the root folder for the current version.
        /// </summary>
        private string versionNamePath = String.Empty;

        /// <summary>
        /// The text containing the version number.
        /// </summary>
        private string text;

        /// <summary>
        /// Initializes a new instance of the Parse class.
        /// </summary>
        public Parse()
        {
        }

        /// <summary>
        /// Gets the build number for the version.
        /// </summary>
        [Output]
        public int BuildNumber
        {
            get
            {
                return this.version.Build;
            }
        }

        /// <summary>
        /// Gets the major number for the version.
        /// </summary>
        [Output]
        public int MajorNumber
        {
            get
            {
                return this.version.Major;
            }
        }

        /// <summary>
        /// Gets the minor number for the version.
        /// </summary>
        [Output]
        public int MinorNumber
        {
            get
            {
                return this.version.Minor;
            }
        }

        /// <summary>
        /// Gets the revision number for the version.
        /// </summary>
        [Output]
        public int RevisionNumber
        {
            get
            {
                return this.version.Revision;
            }
        }

        /// <summary>
        /// Gets or sets the text containing the version number.
        /// </summary>
        [Required]
        public string Text
        {
            get
            {
                return this.text;
            }

            set
            {
                this.text = value;
            }
        }

        /// <summary>
        /// Gets the name of the current version.
        /// </summary>
        [Output]
        public string VersionName
        {
            get
            {
                return this.versionName;
            }
        }

        /// <summary>
        /// Gets the path to the root folder for the current version.
        /// </summary>
        public string VersionNamePath
        {
            get
            {
                return (this.versionNamePath == null ? String.Empty : this.versionNamePath);
            }

            set
            {
                this.versionNamePath = value;
            }
        }

        /// <summary>
        /// Gets the full version number containing the major, minor, build and revision numbers.
        /// </summary>
        [Output]
        public string VersionNumber
        {
            get
            {
                return this.version.ToString();
            }
        }

        /// <summary>
        /// Performs the action of this task.
        /// </summary>
        protected override void InternalExecute()
        {
            // Get the name of the current version from the specified path or fallback to the parent of the current directory
            if (this.versionNamePath.Length >= 1)
            {
                this.versionName = Path.GetFileName(Path.GetFullPath(this.versionNamePath));
            }
            else
            {
                DirectoryInfo currentDirectoryInfo = new DirectoryInfo(Environment.CurrentDirectory);
                this.versionName = currentDirectoryInfo.Parent.Name;
            }

            this.ParseVersionNumber();
        }

        /// <summary>
        /// Parses a version number from some text. The version number can be surrounded by other text.
        /// </summary>
        /// <exception cref="System.InvalidOperationException">Thrown when the text does not contain a single match for the version number.</exception>
        private void ParseVersionNumber()
        {
            Regex versionNumberRegularExpression = new Regex(VersionNumberRegularExpression);
            MatchCollection matches = versionNumberRegularExpression.Matches(this.text);

            // Ensure that a single version number is matched
            if (matches.Count != 1)
            {
                throw new TaskException("VersionNumber.Parse.MustBeSingleMatch", this.text, matches.Count.ToString(CultureInfo.InvariantCulture));
            }

            // Parse the single match for the version number
            this.version = new Version(matches[0].Value);
        }
    }
}
